package com.pearl.security.multiloginreject.demo.session.redis;

import cn.hutool.core.util.StrUtil;
import com.pearl.security.multiloginreject.demo.session.memery.PearlSessionRegistryImpl;
import com.pearl.security.multiloginreject.demo.util.LoginUtils;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.session.SessionInformation;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.session.FindByIndexNameSessionRepository;
import org.springframework.session.Session;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

/**
 * @author TD
 * @version 1.0
 * @date 2024/5/15
 */
public class MySpringSessionBackedSessionRegistry<S extends Session> implements SessionRegistry {
    private final MyFindByIndexNameSessionRepository<S> sessionRepository;

    public MySpringSessionBackedSessionRegistry(MyFindByIndexNameSessionRepository<S> sessionRepository) {
        Assert.notNull(sessionRepository, "sessionRepository cannot be null");
        this.sessionRepository = sessionRepository;
    }

    public List<Object> getAllPrincipals() {
        throw new UnsupportedOperationException("SpringSessionBackedSessionRegistry does not support retrieving all principals, since Spring Session provides no way to obtain that information");
    }

    public List<SessionInformation> getAllSessions(Object principal, boolean includeExpiredSessions) {
        Collection<S> sessions = this.sessionRepository.findByPrincipalName(principal).values();
        List<SessionInformation> infos = new ArrayList<>();
        Iterator<S> var5 = sessions.iterator();
        while (true) {
            Session session;
            do {
                if (!var5.hasNext()) {
                    return infos;
                }
                session = var5.next();
            } while (!includeExpiredSessions && Boolean.TRUE.equals(session.getAttribute(MySpringSessionBackedSessionInformation.EXPIRED_ATTR)));

            infos.add(new MySpringSessionBackedSessionInformation(session, this.sessionRepository));
        }
    }

    public SessionInformation getSessionInformation(String sessionId) {
        S session = this.sessionRepository.findById(sessionId);
        return session != null ? new MySpringSessionBackedSessionInformation(session, this.sessionRepository) : null;
    }

    public void refreshLastRequest(String sessionId) {
    }

    public void registerNewSession(String sessionId, Object principal) {
    }

    public void removeSessionInformation(String sessionId) {
    }

    protected String name(Object principal) {
        return (new TestingAuthenticationToken(principal, (Object) null)).getName();
    }
}
